<template>
  <div>
    <wxc-popover ref="popover-btns"
                 :buttons="popBtns"
                 :position="popoverPosition"
                 :arrowPosition="popoverArrowPosition"
                 @wxcPopoverButtonClicked="popoverButtonClicked"></wxc-popover>

    <list ref="list"
          :showRefresh="true"
          :showLoadMore="showLoadMore"
          @refresh="refresh"
          @loadMore="loadmore"
          loadmoreoffset="100">
      <cell>
        <div class="farm-show">

          <div class="farm-img-wrap"
               @click="goShow">
            <image class="farm-img-bg"
                   :src="farmTopImg"></image>
            <image class="farm-img"
                   :src="farmHeadImg"></image>
            <image class="farm-show-text"
                   src="bmlocal://assets//farm/farm_show_text.png"></image>
          </div>

          <image class="farm-manage"
                 src="bmlocal://assets//farm/farm_manage.jpg"
                 @click="goChickHouse"></image>
        </div>
      </cell>
      <cell>
        <div class="farm-action">
          <div class="farm-action-btn farm-action-btn-dynamic"
               @click="onDynamic">
            <text class="icon farm-action-text farm-action-text-dynamic"
                  style="font-size: 36px;">&#xe609;</text>
            <text class="farm-action-text farm-action-text-dynamic">发布动态</text>
          </div>

          <div class="farm-action-btn farm-action-btn-io"
               @click="goPsi">
            <text class="icon farm-action-text farm-action-text-io"
                  style="font-size: 42px;">&#xe629;</text>
            <text class="farm-action-text farm-action-text-io">进销管理</text>
          </div>
        </div>
      </cell>
      <cell>
        <div class="section">
          <text class="section-title">当前任务</text>
          <text class="section-more"
                @click="goTaskHistory">历史任务</text>
        </div>
      </cell>
      <cell v-for="(task, index) in tasks"
            :key="index">
        <div class="row bg-white border-bottom-light"
             @click="goTask(task)">
          <text class="td-task">{{task.createTime}}</text>
          <text class="td-task">{{task.taskName}}</text>
          <text class="td-task"
                :class="[task.stautsStyle]">{{task.statusName}}</text>
        </div>
      </cell>
      <cell v-if="!hasTask">
        <vm-status empty-text="没有任务~"
                   error-text="获取农场失败"
                   :show-button="isError"
                   :type="isError ? 'error' : 'empty'"
                   @buttonClicked="setFarm(true)"></vm-status>
      </cell>
      <cell v-else-if="!showLoadMore">
        <text class="nomore-text">---- 没有更多任务 ----</text>
      </cell>
    </list>

    <vm-mask height="200"
             width="560"
             :show-close="false"
             :show.sync="dynamicVisible">
      <div class="flex-row p-3 border-bottom"
           @click="goDynamic(1)">
        <text class="icon dynamic-icon">&#xe7de;</text>
        <text class="flex text-right">从相册中选择</text>
      </div>
      <div class="flex-row p-3"
           @click="goDynamic(2)">
        <text class="icon dynamic-icon">&#xe7da;</text>
        <text class="flex text-right">拍摄（照片或视频）</text>
      </div>
    </vm-mask>

  </div>
</template>
<script>
import VmMask from '../../components/vm-mask.vue'
import VmStatus from '../../components/vm-status.vue'
import { WxcPopover } from 'weex-ui'
import {
  DEFAULT_CLIENT_ID,
  STORAGE_USER,
  STORAGE_FARM,
  EVENT_GET_FARM,
  EVENT_GET_USER,
  EVENT_GET_FARM_REFRESH,
  EVENT_GET_USER_REFRESH,
  STORAGE_FIRST_LAUNCH
} from '../../plugins/constant'
import {
  enumTask,
  enumTaskRouter
} from '../../plugins/enumChick'

const globalEvent = weex.requireModule('globalEvent')

export default {
  components: {
    WxcPopover,
    VmMask,
    VmStatus
  },
  props: {},
  data() {
    return {
      user: {},
      farm: {},
      popoverBtns: [
        {
          icon: 'bmlocal://assets//farm/farm_icon_farm.png',
          text: '新建鸡场',
          key: 'farm.create'
        },
        {
          icon: 'bmlocal://assets//farm/farm_icon_farm.png',
          text: '鸡场管理',
          key: 'farm.manage'
        },
        {
          icon: 'bmlocal://assets//farm/farm_icon_product.png',
          text: '产品管理',
          key: 'farm.product'
        },
        {
          icon: 'bmlocal://assets//farm/farm_icon_auth.png',
          text: '认证管理',
          key: 'farm.auth'
        },
        // {
        //   icon: 'bmlocal://assets//farm/farm_icon_cooperate.png',
        //   text: '客户管理',
        //   key: 'farm.cooperate'
        // }
      ],
      popoverPosition: { x: -4, y: 0 },
      popoverArrowPosition: { pos: 'top', x: -42 },
      // 
      dynamicVisible: false,
      // 任务
      params: {
        index: 1,
        size: 20,
        'task_status.eq': 0,
        'task_person.eq': ''
      },
      tasks: [],
      totalPages: 2,
      isError: false,
      errorClickMsg: '获取鸡场失败，请点击刷新按钮重新获取',

      homeBackClickTime: +new Date(),

      // 版本检测
      appVersionInfo: {},
      newest: {},
      downloadUrl: '',
      ignoreVersion: ''
    }
  },
  computed: {
    hasFarm() {
      return this.farm.id && this.farm.id !== DEFAULT_CLIENT_ID
    },
    popBtns() {
      return this.hasFarm ? this.popoverBtns.slice(1) : this.popoverBtns.slice(0, 1)
    },
    farmHeadImg() {
      const images = this.farm.images
      return (images && images.length && images[0]) || 'bmlocal://assets//farm/farm_img_head_default.png'
    },
    farmTopImg() {
      const images = this.farm.farmTopImages
      return (images && images.length && images[0]) || 'bmlocal://assets//farm/farm_bg_default.jpg'
    },
    hasTask() {
      return !this.isError && this.tasks.length
    },
    showLoadMore() {
      return this.totalPages > this.params.index
    }
  },
  watch: {},
  eros: {
    beforeBackAppear(params) {
      if (!params) { return }
      if (params.type === 1) {
        this.setFarm(true)
      } else if (params.type === 3) {
        this.refresh()
      }
    }
  },
  created() {
    this.$event.on(EVENT_GET_USER, res => {
      this.user = res
      res.defaultClientId !== this.farm.id && this.setFarm(true)
    })
    this.$event.on(EVENT_GET_FARM, res => {
      if (res.id === this.farm.id) { return }
      this.farm = res
      this.refresh()
    })

    this.$event.on(EVENT_GET_FARM_REFRESH, () => { this.setFarm() })
    this.$event.on(EVENT_GET_USER_REFRESH, () => { this.setUser() })

    this.$navigator.setRightItem({
      image: 'bmlocal://assets//icon_add.png'
    }, this.addButtonClick)

    this.getUser()

    this.androidFinishApp()
    this.checkVersion()
  },
  methods: {
    androidFinishApp() {
      globalEvent.addEventListener('homeBack', options => {
        const timeNow = new Date().getTime()
        if (timeNow - this.homeBackClickTime > 2000) {
          this.$notice.toast({ message: '再按一次退出应用' })
          this.homeBackClickTime = timeNow
        } else {
          this.$router.finish()
        }
      })
    },
    getUser() {
      this.user = this.$storage.getSync(STORAGE_USER) || {}
      this.farm = this.$storage.getSync(STORAGE_FARM) || {}
      if (this.farm.id) {
        // 当农场id为默认id，也要去获取任务，为创建农场的任务
        this.refresh()
      } else {
        this.setUser()
      }
    },
    setUser() {
      this.$http({
        method: 'GET',
        name: 'auth.me'
      }).then(res => {
        this.user = res
        this.$storage.setSync(STORAGE_USER, res)
        this.$event.emit(EVENT_GET_USER, res)
        if (res.defaultClientId !== this.farm.id) {
          this.getFarmInfo()
        }
      }).catch(err => {
        this.showErrorDialog(err, '获取个人信息失败')
      })
    },
    getFarmInfo() {
      // 从storage中获取农场信息
      const farm = this.$storage.getSync(STORAGE_FARM)
      if (farm) {
        return this.$event.emit(EVENT_GET_FARM, farm)
      }
      this.setFarm()
    },
    setFarm(showLoading = false) {
      const farmId = this.user.defaultClientId || this.farm.id || DEFAULT_CLIENT_ID
      if (farmId === DEFAULT_CLIENT_ID) { return }
      showLoading && this.$notice.loading.show("获取鸡场中...")
      this.$http({
        method: 'GET',
        name: 'industrial.farm.info',
        data: {
          farmId: farmId
        }
      }).then(res => {
        this.isError = false
        this.farm = res
        this.$storage.setSync(STORAGE_FARM, res)
        this.$event.emit(EVENT_GET_FARM, res)
        this.refresh()
      }).catch(err => {
        const errDesc = err && err.errorMsg && err.errorMsg.errorDescription || ''
        if (errDesc.indexOf('农场不存在') > -1) {
          // 农场不存在
          this.isError = false
          this.tasks = [{
            createTime: this.$utils.dateFormat(new Date(), 'yyyy.MM.dd'),
            taskName: '创建鸡场',
            stautsStyle: 'text-danger',
            statusName: '去创建',
            type: 0
          }]
        } else {
          this.isError = true
          this.showErrorDialog(err, '获取鸡场失败')
        }
      }).finally(() => {
        showLoading && this.$notice.loading.hide()
      })
    },
    // 加号按钮
    addButtonClick() {
      this.$refs['popover-btns'].wxcPopoverShow();
    },
    popoverButtonClicked({ key }) {
      if (!this.checkError(false)) { return }
      this.$nav.open({ name: key })
    },
    // 发布动态
    onDynamic() {
      if (!this.checkError()) { return }
      this.dynamicVisible = true
    },
    goDynamic(type) {
      this.dynamicVisible = false
      if (type === 1) {
        this.selectPicture(type)
      } else if (type === 2) {
        this.selectCamera(type)
      }
    },
    selectPicture(type) {
      this.$picture.pick({
        maxCount: 9
      }).then(res => {
        this.$nav.open({
          name: 'farm.dynamic',
          params: {
            farm: this.farm,
            images: res || [],
            type
          }
        })
      }).catch(err => {
        this.$notice.toast({ message: '选择图片失败，请重试！' })
      })
    },
    selectCamera(selectType) {
      this.$picture.video({}).then(({ type, data }) => {
        const params = { farm: this.farm }
        if (type === 'capture') {
          params.images = data
          params.type = 1
        } else {
          params.video = data[0] || ''
          params.thumb = data[1] || ''
          params.type = 2
        }
        this.$nav.open({
          name: 'farm.dynamic',
          params
        })
      }).catch(err => {
        this.$notice.toast({ message: '视频拍摄失败，请重试！' })
      })
    },
    goShow() {
      if (!this.checkError()) { return }
      this.$nav.open({ name: 'farm.show' })
    },
    checkError(checkFarm = true) {
      if (this.isError) {
        this.$notice.toast({ message: this.errorClickMsg })
        return false
      } else if (checkFarm && !this.hasFarm) {
        this.$notice.toast({ message: '请选创建鸡场' })
        return false
      }
      return true
    },
    // 任务
    refresh() {
      this.params.index = 1
      this.getTask().then(res => {
        this.tasks = res
      }).finally(() => this.$refs["list"].refreshEnd())
    },
    loadmore() {
      if (!this.showLoadMore) {
        return this.$refs["list"].loadMoreEnd()
      }
      this.params.index += 1
      this.getTask().then(res => {
        this.tasks.push(...res)
      }).finally(() => this.$refs["list"].loadMoreEnd())
    },
    getTask() {
      return new Promise((resolve, reject) => {
        this.params['task_person.eq'] = this.farm.id
        this.$api.getData({
          server: 'agr_chain',
          table: 'task_list',
          params: this.params,
          order: {
            N1create_time: 'desc',
            N2task_type: 'asc'
          }
        }).then(res => {
          this.totalPages = res && res.totalPages || 0
          const data = res && res.data || []
          resolve(data.map(item => {
            item.createTime = this.$utils.dateFormat(item.create_time, 'yyyy.MM.dd')
            item.taskName = enumTask[item.task_type] || '其他任务'
            item.statusName = +item.task_status === 0 ? '未处理' : '已处理'
            item.stautsStyle = +item.task_status === 0 ? 'text-warning' : ''
            // 已超时标红色 -> 6点前未处理标红色
            const nowDate = this.$utils.dateFormat(new Date(), 'yyyy.MM.dd')
            if (nowDate !== item.createTime || new Date().getHours() >= 18) {
              item.stautsStyle = 'text-error'
            }
            return item
          }))
        }).catch(err => {
          this.showErrorDialog(err, '任务获取失败')
          reject(err)
        })
      })

    },
    goTask(task) {
      const type = enumTaskRouter[task.task_type]
      if (!type) { return }
      this.$nav.open({
        name: type,
        params: { task }
      })
    },
    goTaskHistory() {
      if (!this.checkError()) { return }
      this.$nav.open({
        name: 'farm.task.history'
      })
    },
    goPsi() {
      if (!this.checkError()) { return }
      this.$nav.open({
        name: 'farm.psi'
      })
    },
    goChickHouse() {
      if (!this.checkError()) { return }
      this.$nav.open({
        name: 'farm.feed.manage'
      })
    },

    // 没有登录或登录过期
    showErrorDialog(err, des) {
      if (err && err.status === 403) {
        return this.$dialog.show({
          title: '提示',
          content: `还没有登录或登录过期，请重新登录！`,
          positiveText: '去登录',
          negativeText: '取消',
          onPositive: () => {
            this.goLogin()
          }
        })
      }

      const msg = err.gmMessage || des
      this.$notice.toast({ message: msg })
    },
    goLogin() {
      this.$storage.removeAllSync()
      this.$storage.setSync(STORAGE_FIRST_LAUNCH, '1')
      this.$router.setHomePage('/pages/user/login.js')
    },

    // 版本检查
    checkVersion() {
      Promise.all([this.getVersionInfo(), this.getNesest()]).then(res => {
        this.appVersionInfo = res[0] || {}
        this.newest = res[1] || {}
        this.getDownloadUrl().then(res => {
          this.downloadUrl = res
          this.checkUpdate()
        })
      }).catch(err => {
        console.log(err)
      })
    },
    checkUpdate() {
      // 无法获取版本信息、版本号大于等于最新版本
      const newestCode = +this.newest.version_code || 0
      if (!this.appVersionInfo.versionCode ||
        !this.newest.version_code ||
        (this.appVersionInfo.versionCode >= newestCode)
      ) { return }

      this.ignoreVersion = this.$storage.getSync(STORAGE_VERSION_IGNORE) || ''
      if (this.ignoreVersion && +this.ignoreVersion === newestCode) { return }

      this.$dialog.show({
        title: '发现新版本',
        content: this.newest.description || '',
        positiveText: '立即更新',
        negativeText: '取消',
        neutralText: '忽略该版本',
        onPositive: () => {
          this.startDownloadAndInstall()
        },
        onNeutral: () => {
          this.$storage.setSync(STORAGE_VERSION_IGNORE, newestCode)
        }
      })
    },
    getVersionInfo() {
      return new Promise(async (resolve, reject) => {
        const [res, err] = await this.$utils.pm(this.$version.getVersionInfo())
        if (res) { resolve(res) } else { reject(err) }
      })
    },
    getNesest() {
      return new Promise(async (resolve, reject) => {
        const [res, err] = await this.$utils.pm(this.$api.getData({
          server: 'agr_chain',
          table: 'app_version_view',
          params: {
            index: 1,
            size: 1,
            'release_status.eq': 1
          },
          order: {
            version_code: 'desc'
          },
          errorMsg: '获取数据失败'
        }))
        if (res && res.data && res.data.length) {
          const item = res.data[0]
          item.links = []
          item.description = item.description ? item.description.replace(/<br\/>/g, '\n').replace(/&nbsp;/g, ' ') : ''
          const channelNames = this.getSplit(item.channel_name)
          const channelUrls = this.getSplit(item.channel_url)
          const channelIds = this.getSplit(item.channel_id)
          for (let i = 0; i < channelNames.length; i++) {
            item.links.push({
              channelId: channelIds[i],
              channelName: channelNames[i],
              channelUrl: channelUrls[i]
            })
          }
          resolve(item)
        } else {
          reject(err)
        }
      })
    },
    getSplit(str, splitor = ',') {
      return str ? str.split(splitor) : []
    },
    // 从最新版本获取对应渠道的下载地址
    getDownloadUrl() {
      return new Promise((resolve, reject) => {
        const links = this.newest.links || []
        if (!links.length) {
          return reject('无下载地址')
        }
        let downloadUrl = ''
        let defaultUrl = ''
        for (const link of links) {
          if (link.channelId === this.appVersionInfo.channel) {
            downloadUrl = link.channelUrl
            break
          }
          if (link.channelId === 'WeiMi') {
            defaultUrl = link.channelUrl
          }
        }
        if (!downloadUrl) {
          downloadUrl = defaultUrl
        }
        if (!downloadUrl) {
          reject('无下载地址')
        } else {
          resolve(downloadUrl)
        }
      })
    },
    startDownloadAndInstall() {
      if (!this.downloadUrl) {
        return this.$notice.toast({ message: '无下载地址' })
      }
      this.$version.downloadAndInstall({
        downloadUrl: this.downloadUrl,
        versionTips: this.newest.version_tips
      }).then(res => {
        this.$notice.toast({ message: '开始下载，下载完成后自动安装' })
      })
    },
  }
}

</script>
<style lang="scss"
       scoped>
@import "../../css/variables.scss";
@import "../../css/common.scss";

.icon {
  font-family: alicon;
}

.text-white {
  color: #fff;
}
.flex-row {
  flex-direction: row;
}
.flex {
  flex: 1;
}
.text-right {
  text-align: right;
}
.border-bottom {
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.border-bottom-light {
  border-bottom-width: 1px;
  border-bottom-color: $gray-100;
}
.p-3 {
  padding: 30px;
}
.px-3 {
  padding-left: 30px;
  padding-right: 30px;
}
.py-1 {
  padding-top: 10px;
  padding-bottom: 10px;
}
.py-2 {
  padding-top: 20px;
  padding-bottom: 20px;
}
.py-3 {
  padding-top: 30px;
  padding-bottom: 30px;
}
.bg-white {
  background-color: #fff;
}

.scroller {
  flex: 1;
}

.nav-brand {
  color: #fff;
  font-size: 32px;
  padding-left: 30px;
  padding-right: 30px;
}

.nav-search {
  background-color: #7ad188;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  flex: 1;
  height: 60px;
  line-height: 60px;
  border-radius: 30px;
}

.nav-search-text {
  color: #e2f5e5;
  font-size: 28px;
}

.nav-action {
  color: #fff;
  font-size: 52px;
}

.farm-show {
  // padding: 15px;
  background-color: #fff;
  flex-direction: row;
  // box-shadow: 3px 3px 6px rgba(26, 26, 26, 0.2);
}

.farm-img-wrap {
  width: 220px;
  height: 220px;
  margin: 15px;
  border-radius: 6px;
  padding-top: 15px;
  padding-bottom: 15px;
  align-items: center;
  background-color: #666;
  // box-shadow: 0 0 6px rgba(26, 26, 26, 0.2);
}

.farm-img-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 220px;
  height: 220px;
  opacity: 0.5;
}

.farm-img {
  width: 140px;
  height: 140px;
  border-radius: 70px;
  border-style: solid;
  border-color: #fff;
  border-width: 4px;
  margin-bottom: 10px;
}

.farm-show-text {
  width: 140px;
  height: 32px;
}

.farm-manage {
  width: 485px;
  height: 220px;
  border-radius: 6px;
  margin-top: 15px;
}

.farm-action {
  width: 750px;
  flex-direction: row;
  padding-left: 15px;
  padding-right: 15px;
  padding-bottom: 15px;
  background-color: #fff;
}

.farm-action-btn {
  flex: 1;
  height: 96px;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  border-width: 1px;
  border-style: solid;
}

.farm-action-btn-dynamic {
  margin-right: 15px;
  background-color: #fde6d2;
  border-color: #f37b1d;
}

.farm-action-btn-dynamic:active {
  background-color: #e9b38a;
}

.farm-action-btn-io {
  background-color: #d2f1f0;
  border-color: #1cbbb4;
}

.farm-action-btn-io:active {
  background-color: #7ae2dd;
}

.farm-action-text {
  font-size: 32px;
  padding-left: 5px;
  padding-right: 5px;
}

.farm-action-text-dynamic {
  color: #f37b1d;
}

.farm-action-text-io {
  color: #1cbbb4;
}

.font-weight-bold {
  font-weight: 900;
}

.section {
  width: 750px;
  padding-left: 15px;
  padding-right: 15px;
  padding-top: 30px;
  padding-bottom: 20px;
  background-color: #fff;
  border-bottom-style: solid;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
  margin-top: 15px;
  flex-direction: row;
  align-items: center;
}

.section-title {
  flex: 1;
  font-size: 32px;
}

.section-more {
  color: #999;
  font-size: 28px;
}

.container {
  width: 750px;
  padding: 15px;
  background-color: #fff;
}

.text {
  font-size: 28px;
}

.dynamic-icon {
  font-size: 36px;
  color: $accent;
}

.td-task {
  flex: 1;
  font-size: 28px;
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 25px;
  padding-bottom: 25px;
  text-align: center;
}

.nomore-text {
  padding: 30px;
  font-size: 22px;
  text-align: center;
  color: #999;
}
</style>
